<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\Message;
use plugin\admin\app\model\MessageChat;

class CustomerService
{
    public static function add($userId, $messageType, $messageContent, $role = Message::ROLE_SYSTEM)
    {
        if (!($chat = MessageChat::where('user_id', $userId)->first())) {
            $chat = new MessageChat();
        }

        Message::insert([
            'role' => $role,
            'user_id' => $userId,
            'message_type' => $messageType,
            'content' => $messageContent,
            'created_time' => date('Y-m-d H:i:s')
        ]);

        $chat->user_id = $userId;
        $chat->last_message_type = $messageType;
        $chat->last_message_content = $messageContent;
        $chat->last_message_created_time = date('Y-m-d H:i:s');
        $chat->save();
    }

    public static function list($userId, $page, $length = 10, $pagation = true)
    {
        $offset = ($page - 1) * $length;
        $query =  Message::where('user_id', $userId);

        if (!$pagation) {
            return $query->get()->toArray();
        }
        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->orderByDesc('created_time')->get()->toArray();

        usort($list, function($a, $b) {
            return $a['id'] > $b['id'];
        });

        return Page::wrap($totalCount, $page, $length, $list);
    }
}